package com.mk.legoscans2.activities;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.android.gcm.GCMRegistrar;
import com.mk.legoscans2.LegoScans3Application;
import com.mk.legoscans2.Message;
import com.mk.legoscans2.R;
import com.mk.legoscans2.Scan;
import com.mk.legoscans2.StartItemOnTouchListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.RelativeLayout;

public class StartActivity extends Activity {
	
	private SimpleDateFormat _messageDateFormat = new SimpleDateFormat("EEE, MMM d");
	private DownloadNewMessagesTask _downloadNewMessagesTask;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start);
		
		/*The checkDevice() method verifies that the device supports GCM and throws an exception if it does not (for instance, if it is an emulator that does not contain the Google APIs). Similarly, the checkManifest() method verifies that the application manifest contains meets all the requirements described in Writing the Android Application (this method is only necessary when you are developing the application; once the application is ready to be published, you can remove it).*/
		GCMRegistrar.checkManifest(this);
		try{
			GCMRegistrar.checkDevice(this);
			final String regId = GCMRegistrar.getRegistrationId(this);
			if (regId.equals("")) {
				GCMRegistrar.register(this, LegoScans3Application.GCMSenderId);
			} else {
				if(LegoScans3Application.getApplicationVersionCode() != LegoScans3Application.ApplicationPreferences.getGcmRegistrationVersion())
					GCMRegistrar.unregister(this);

				Log.v("INFO", "Already registered, regId: " + regId);
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		
		_downloadNewMessagesTask = new DownloadNewMessagesTask(this);
		_downloadNewMessagesTask.execute();
		
		RelativeLayout searchContainer = (RelativeLayout)findViewById(R.id.start_search_container);
		RelativeLayout themesContainer = (RelativeLayout)findViewById(R.id.start_themes_container);
		RelativeLayout favoritesContainer = (RelativeLayout)findViewById(R.id.start_favorites_container);
		RelativeLayout settingsContainer = (RelativeLayout)findViewById(R.id.start_settings_container);
		
		searchContainer.setOnTouchListener(new StartItemOnTouchListener(this, searchContainer, new Intent(this, SearchActivity.class)));
		themesContainer.setOnTouchListener(new StartItemOnTouchListener(this, themesContainer, new Intent(this, BrowseByThemeActivity.class)));
		favoritesContainer.setOnTouchListener(new StartItemOnTouchListener(this, favoritesContainer, new Intent(this, FavoritesScanListActivity.class)));
		
		settingsContainer.setOnTouchListener(new StartItemOnTouchListener(this, settingsContainer, new Intent(this, SettingsActivity.class)));
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if(_downloadNewMessagesTask != null) {
			_downloadNewMessagesTask.cancel(true);
			_downloadNewMessagesTask = null;
		}
	}
	
	private class DownloadNewMessagesTask extends AsyncTask<String, Void, Map<Message, List<Scan>>> {

		private Activity _activity;
		private int _lastMessageId;
		
		public DownloadNewMessagesTask(Activity activity)
		{
			_activity = activity;
		}
		
		@Override
		protected void onPreExecute() {
			_lastMessageId = LegoScans3Application.ApplicationPreferences.getLastMessageId();
		}
		
		@Override
		protected Map<Message, List<Scan>> doInBackground(String... params) {
			Map<Message, List<Scan>> messages = new HashMap<Message, List<Scan>>();
			List<Message> m = LegoScans3Application.MessageService.getNewMessages(_lastMessageId);
			if(m != null) {
				for (Message message : m) {
					List<Scan> scans = message._type.equals("NewContent") ? LegoScans3Application.ApiRepository.getScansByQuery(message._msg.replace(";", " ")) : null;
					messages.put(message, scans);
				}
			}
			return messages;
		}
		
		@Override
		protected void onPostExecute(Map<Message, List<Scan>> result) {
			if(!_activity.isFinishing())
			{
				if(result != null && result.size() > 0)
				{
					StringBuilder builder = new StringBuilder();
					
					for (Message message : result.keySet()) {
						LegoScans3Application.ApplicationPreferences.setLastMessageId(message._id);
						
						if(_lastMessageId != 0) {
							AddMessage(message, result.get(message), builder);
						}
					}
					
					AlertDialog.Builder messageDialogbuilder = new AlertDialog.Builder(_activity);
					messageDialogbuilder.setTitle(_lastMessageId == 0 ? "Welcome to Lego Scans!" : "What's new?")
						.setMessage(_lastMessageId == 0 ? "Hi there!\nTo get started just tap either 'Search' or 'Themes' and start browsing through over 4000 scans!\n\nIf you enjoy this app, please rate it in Android Market!\n\nHave fun!" : builder.toString())
						.setPositiveButton("Alright", new OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						})
						.show();
				}
			}
		}

		private void AddMessage(Message message, List<Scan> scans, StringBuilder builder) {
			builder.append(_messageDateFormat.format(message._timeStamp) + "\n");
			
			if(message._type.equals("NewContent") && scans != null) {
				builder.append(scans.size() + " new scans added:\n");
				for (Scan scan : scans) {
					builder.append("#" + scan._boxNumber + " " + scan._name + " (" + scan._theme + ")\n");
				}
			}
			else {
				builder.append(message._msg + "\n\n");
			}
		}
	}
}